import { assetsDB } from '@/indexDB/index'
import { EXCHANGE_LIST_KEY } from '@/views/hold/model'

export interface ExchangeItem {
  id?: string | number
  holdId: string | number // 持仓的id
  type: 'sell' | 'buy'  // 交易方向
  count?: number // 数量
  price?: number // 单价
  createTime?: string
  remarks?: string //备注
}

export const exchangeKeys = '++id, holdId, type, count, price, createTime, remarks'


export const initExchangeDB = async () => {
  const arr = await assetsDB.exchangeList.toArray()
  if (!arr.length) {
    const listStr = localStorage.getItem(EXCHANGE_LIST_KEY)
    const list = listStr ? JSON.parse(listStr) : []
    const formattedList: ExchangeItem[] = list.map((exchange: ExchangeItem) => {
      // 以前的id是持仓id-holdId
      const { id } = exchange
      return {
        ...exchange,
        holdId: id
      }
    })

    await assetsDB.exchangeList.bulkPut(formattedList)
    console.log('交易记录迁移成功!');
  }
}
